#!/usr/bin/env bash -e

trap 'kill %1; kill %2' SIGINT

cmd_ps() {
    nodenames=`echo $@ | sed 's/\ / node-/g;s/^/node-/'`
    set -x
    docker-compose ps $nodenames
}

cmd_up() {
    for i in $@; do
        if [[ $i = *"farmer"* ]]; then continue; fi
        mkdir -p $i
        #ln -sf ../.compose.tpl $i/docker-compose.yml
        user=$USER
        gqlport=$((12800+$i))
        grpcport=$((12900+$i))
        if [ ! -f $i/docker-compose.yml ]; then
            > $i/docker-compose.part
            echo "  node-$i:" >> $i/docker-compose.part
            echo "    container_name: 'dev-$user-$i'" >> $i/docker-compose.part
            echo "    environment:" >> $i/docker-compose.part
            echo "      USER: 'dev-$user-$i'" >> $i/docker-compose.part
            echo "    ports:" >> $i/docker-compose.part
            echo "      - $grpcport:$grpcport" >> $i/docker-compose.part
            echo "      - $gqlport:$gqlport" >> $i/docker-compose.part
            echo "    image: bertytech/berty:latest" >> $i/docker-compose.part
            echo "    network_mode: bridge" >> $i/docker-compose.part
            echo "    command: daemon --grpc-bind=0.0.0.0:$grpcport --gql-bind=0.0.0.0:$gqlport" >> $i/docker-compose.part
        fi
    done
    > docker-compose.yml
    echo "version: '3'" >> docker-compose.yml
    echo "" >> docker-compose.yml
    echo "services:" >> docker-compose.yml
    cat [0-9]*/docker-compose.part >> docker-compose.yml
    for i in $@; do
        if [[ $i = *"farmer"* ]]; then continue; fi
        (
            set -x
            docker-compose up -d node-$i
        )
    done
}

cmd_stop() {
    nodenames=`echo $@ | sed 's/\ / node-/g;s/^/node-/'`
    set -x
    docker-compose stop $nodenames || true
}

cmd_down() {
    for i in $@; do
        if [[ $i = *"farmer"* ]]; then continue; fi
        if [ ! -d "$i" ]; then echo "no such node: $i"; continue; fi
        (
            set -x
            docker-compose kill -s 9 node-$i
            docker-compose rm -f node-$i
            rm -rf $i
        )
    done
}

cmd_logs() {
    nodenames=`echo $@ | sed 's/\ / node-/g;s/^/node-/'`
    set -x
    docker-compose logs -f $nodenames
}

cmd_info() {
    nodenames=`echo $@ | sed 's/\ / node-/g;s/^/node-/'`
    docker-compose logs $nodenames | grep grpc\ server\ started | grep 'user-id....[^"]*"'
}

cmd_build() {
    set -x
    docker build -t bertytech/berty ../..
}

# FIXME: implement cmd_client (that runs a 'berty client --node-address=XXX $cmd')

cmd=$1
shift
nodes=$@
if [ $# -lt 1 ]; then
    nodes=[0-9]*
fi
case $cmd in
    build)   cmd_build;;
    up)      cmd_up $nodes;;
    stop)    cmd_stop $nodes;;
    down)    cmd_down $nodes;;
    logs)    cmd_logs $nodes;;
    ps)      cmd_ps $nodes;;
    info)    cmd_info $nodes;;
    *)       echo "Usage $0 {build|{up|ps|stop|down|logs} ID...}"; exit 1
esac
